package org.study.article.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.study.article.dao.ArticleDao;
import org.study.article.dao.mapper.ArticleMapper;
import org.study.article.dao.mapper.ArticleRecordTabMapper;
import org.study.article.model.ArticleRecord;
import org.study.article.model.ArticleRecordTab;
import org.study.article.model.vo.ArticleRecordSubmitVo;
import org.study.article.service.ArticleService;

import com.google.common.collect.Maps;

import java.util.List;
import java.util.Map;

@Service
public class ArticleServiceImpl implements ArticleService {
    @Autowired
    ArticleDao articleDao;
    @Autowired
    ArticleRecordTabMapper artMapper;
    @Autowired
    ArticleMapper aMapper;
    
    @Transactional
    @Override
    public int insert(ArticleRecordSubmitVo data) {
    	aMapper.insert((ArticleRecord)data);
        refrashTabs(data);
    	return 0;
    }

    @Override
    public List<ArticleRecord> listAll() {
        return articleDao.listAll();
    }

    @Override
    public ArticleRecord listById(int id) {
        return aMapper.selectById(id);
    }

    @Override
    public List<ArticleRecord> listByUid(int uid) {
    	Map<String, Object> params = Maps.newHashMap();
    	params.put("create_user_id", uid);
        return aMapper.selectByMap(params);
    }
    @Override
    public ArticleRecord selectByPrimaryKey(Long id) {
        return articleDao.selectByPrimaryKey(id);
    }

    @Override
    public void update(ArticleRecordSubmitVo data) {
        int i = aMapper.updateById(data);
        Map<String,Object> params = Maps.newHashMap();
        params.put("article_record_id",data.getId());
        artMapper.deleteByMap(params);
        refrashTabs(data);
    }

    private void refrashTabs(ArticleRecordSubmitVo data) {
        List<String> tabs = data.getTabs();
        if(tabs!=null &&!tabs.isEmpty()) {
            ArticleRecordTab tab;
            for (String articleRecordTab : tabs) {
                tab = new ArticleRecordTab();
                tab.setTab(articleRecordTab);
                tab.setArticleRecordId(data.getId());
                artMapper.insert(tab);
            }
        }
    }
}
